package com.jdk.demo.thread.completableFuture;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

public class AllOfDemo {
	
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		List<String> webPageLinks = Arrays.asList("www.baidu.com", "www.sohu.com", "www.sina.com");
		List<CompletableFuture<String>> pageContentFutures = webPageLinks.stream().map(webPageLink -> downloadWebPage(webPageLink))
				.collect(Collectors.toList());
		CompletableFuture<Void> allFutures = CompletableFuture.allOf(pageContentFutures.toArray(new CompletableFuture[pageContentFutures.size()]));
		// 因为allOf没有返回值，所以通过thenApply，给allFutures附上一个回调函数。在回调函数里面，依次调用每个future的get()函数，获取到100个结果，存入List<String>
		CompletableFuture<List<String>> allPageContentsFuture = allFutures.thenApply(v ->{
			return pageContentFutures.stream().map(pageContentFuture -> {
				try{
					return pageContentFuture.get();
				}catch(Exception e) {
					
				}
				return null;
			}).collect(Collectors.toList());
		});
		// 统计在这100个网页中，含有单词“XXX”的网页的个数
		CompletableFuture<Long> countFuture = allPageContentsFuture.thenApply(pageContents -> {
			return pageContents.stream().filter(pageContent -> pageContent.contains("XXX")).count();
		});
		System.out.println(countFuture.get());
	}

	private static CompletableFuture<String> downloadWebPage(String url) {
		return CompletableFuture.supplyAsync(() -> {
			if(url.equals("www.baidu.com"))
				return "XXX";
			else if(url.equals("www.sohu.com"))
				return "XXX";
			else
				return "zzz";
		});
	}

}
